package com.experienceBaby.Cashbook.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.TimePickerView;
import com.experienceBaby.Cashbook.R;
import com.experienceBaby.Cashbook.adapter.ItemAdapter;
import com.experienceBaby.Cashbook.bean.Item;
import com.experienceBaby.Cashbook.databinding.FragmentAdditemBinding;
import com.experienceBaby.Cashbook.greendao.DbController;
import com.experienceBaby.Cashbook.greendao.db.Recode;
import com.experienceBaby.Cashbook.utils.DateUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class AddItemFragment extends Fragment {
    private FragmentAdditemBinding binding;
    private DbController dbController;
    private ItemAdapter itemAdapter;

    public Date time;
    public int year, month, date;

    List<Item> items;

    private boolean isIncome;

    public AddItemFragment(DbController dbController, boolean isIncome) {
        this.dbController = dbController;
        this.isIncome = isIncome;
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = FragmentAdditemBinding.inflate(inflater, container, false);
        initData();
        initView();
        return binding.getRoot();
    }

    private void initData() {
        items = new ArrayList<>();
        if (!isIncome) {
            items.add(new Item(R.drawable.canyin, R.drawable.canyin_blue, "餐饮"));
            items.add(new Item(R.drawable.gouwu, R.drawable.gouwu_blue, "购物"));
            items.add(new Item(R.drawable.riyong, R.drawable.riyong_blue, "日用"));
            items.add(new Item(R.drawable.yule, R.drawable.yule_blue, "娱乐"));
            items.add(new Item(R.drawable.fushi, R.drawable.fushi_blue, "服饰"));
        } else {
            items.add(new Item(R.drawable.shenghuofei, R.drawable.shenghuofei_blue, "生活费"));
            items.add(new Item(R.drawable.gongzi, R.drawable.gongzi_blue, "工资"));
            items.add(new Item(R.drawable.jianzhi, R.drawable.jianzhi_blue, "兼职"));
            items.add(new Item(R.drawable.hongbao, R.drawable.hongbao_blue, "红包"));
        }
        time = new Date();
        year = time.getYear() + 1900;
        month = time.getMonth() + 1;
        itemAdapter = new ItemAdapter(getContext(), items);
    }

    private void initView() {
        binding.grid.setAdapter(itemAdapter);
        setListener();
    }

    private void setListener() {
        binding.calendaradd.setOnClickListener(view -> {
            TimePickerView pvTime = new TimePickerView.Builder(view.getContext(), new TimePickerView.OnTimeSelectListener() {
                @Override
                @Deprecated
                public void onTimeSelect(Date date1, View v) {
                    time = date1;
                    year = date1.getYear() + 1900;
                    month = date1.getMonth() + 1;
                    date = date1.getDate();
                    if (DateUtils.getDate(date1.getTime()).getTime() == DateUtils.getDate(new Date().getTime()).getTime()) {
                        binding.date.setText("今天");
                    } else {
                        binding.date.setText(year + "年" + String.format("%02d", month) + "月" + String.format("%02d", date) + "日");
                    }
                }
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                    .setSubmitText("确定")//确定按钮文字
                    .setCancelText("取消")//取消按钮文字
                    .setTitleText("请选择")//标题
                    .setSubCalSize(18)//确定和取消文字大小
                    .setTitleSize(20)//标题文字大小
                    .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                    .isCyclic(false)//是否循环滚动
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .setDividerColor(Color.YELLOW)//设置分割线的颜色
                    .setContentSize(21)//滚轮文字大小
                    .setLineSpacingMultiplier(1.2f)//设置两横线之间的间隔倍数
                    .setTextXOffset(-10, 0, 10, 0, 0, 0)//设置X轴倾斜角度[ -90 , 90°]
                    .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                    .setDecorView(null)//设置要将pickerview显示到的容器id 必须是viewgroup
                    .isDialog(false)//是否显示为对话框样式
                    .build();
            pvTime.show();
        });
        binding.btnSubmit.setOnClickListener(view -> {
            if (insert()) {
                showToast("添加成功！");
                DetailFragment.handler.sendEmptyMessage(2);
                Objects.requireNonNull(getActivity()).finish();
            }
        });
    }

    private boolean insert() {
        if (itemAdapter.getSelect() == -1) {
            showToast("请选择账单类型");
            return false;
        }
        String c = binding.etCost.getText().toString();
        if (c.isEmpty()) {
            showToast("请输入金额");
            return false;
        }
        double cost = Double.parseDouble(binding.etCost.getText().toString());
        Recode recode = new Recode();
        recode.setRemark(binding.etRemark.getText().toString());
        recode.setType(items.get(itemAdapter.getSelect()).getText());
        recode.setDate(time.getTime());
        recode.setSDate(DateUtils.getS_Date(time));
        recode.setYear(year);
        recode.setMonth(month);
        recode.setCost(cost);
        recode.setIncome(isIncome ? 1 : 0);
        dbController.insert(recode);
        return true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void showToast(String text) {
        Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
    }
}
